<template>
  <div class="ag-cell-edit-wrapper">
    <el-select v-bind="params?.componentProps"
               v-model="selectedValue"
               :popper-class="AG_EDITOR_SELECT"
               filterable
               :filter-method="filterMethod"
    >
      <el-option
        v-for="option in filteredOptions"
        :key="option[params?.valueField || 'value']"
        :label="option[params?.labelField || 'label']"
        :value="option[params?.valueField || 'value']"
        :disabled="option[params?.disabledField || 'disabled'] === (params?.disabledValue === undefined ? true : params?.disabledValue)"
      />
    </el-select>
  </div>

</template>

<script lang="ts" setup>
import { onMounted, ref, defineComponent, PropType,watch } from 'vue'
import { ElSelect, ElOption } from "element-plus";
import { CellEditorParams, AG_EDITOR_SELECT } from "@/components/ag-grid/editor/index";


interface SelectCellEditorParam extends CellEditorParams {
  options: any[]
  labelField: string
  valueField: string
  disabledField: string
  disabledValue: string | number | boolean
}

interface Props {
  params: SelectCellEditorParam
}


const props = defineProps<Props>()
const filteredOptions = ref([]);  // 需要初始化为空数组
const selectedValue = ref(null)
// 监听 params 变化，确保值正确更新
watch(() => props.params, (newParams) => {
  if (newParams) {
    selectedValue.value = newParams.value
    filteredOptions.value = newParams.options || []
    console.log('watch selectedValue.value', JSON.stringify(selectedValue.value))
    console.log('watch filteredOptions.value', JSON.stringify(filteredOptions.value))
  }
}, { immediate: true })
onMounted(() => {
  //debugger;
  selectedValue.value = props.params?.value
  filteredOptions.value = props.params?.options || []
  console.log('onMounted filteredOptions.value', JSON.stringify(filteredOptions.value))
})

/**
 * the final value to send to the grid, on completion of editing
 */
function getValue() {
  return selectedValue.value
}

// 开始编辑之前 是否需要取消编辑
/**
 * Gets called once before editing starts, to give editor a chance to cancel the editing before it even starts.
 */
function isCancelBeforeStart() {
  return false
}

/**
 * Gets called once when editing is finished (eg if Enter is pressed). If you return true, then the result of the edit will be ignored.
 */
function isCancelAfterEnd() {
  return false
}
// 自定义过滤方法 - 实现模糊匹配
function filterMethod(query) {
  if (!query) {
    // 如果没有查询词，显示所有选项
    filteredOptions.value = props.params?.options || [];
  } else {
    // 根据组合名称(combinationName)进行模糊匹配
    filteredOptions.value = (props.params?.options || []).filter(item => {
      return item[props.params?.labelField || 'label'].toLowerCase().includes(query.toLowerCase());
    });
  }
}

defineExpose({
  getValue,
  isCancelBeforeStart,
  isCancelAfterEnd,
})

</script>
